package com.gitee.feizns.dynamic.convert.impl;

import com.gitee.feizns.dynamic.DateUtils;
import com.gitee.feizns.dynamic.convert.AbstractConverter;
import com.gitee.feizns.dynamic.convert.ParseToDateTypeUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * <b>从任意类型转换为时间时间戳</b>
 * <p>
 *     这个转换器引用了{@link ParseToDateTypeUtils}如果希望支持更多的字符串日期格式
 *     可以在全局中注册{@link ParseToDateTypeUtils#register(String)}
 * </p>
 * @see ParseToDateTypeUtils
 * @author feizns
 * @since 2022/11/17
 */
public class ToTimestampConverter extends AbstractConverter<Object, Long> {

    /**
     * 支持转换的类型
     */
    private static final Set<Class<?>> SUPPORT_SOURCE_CLASSES = new HashSet<>();

    static {
        SUPPORT_SOURCE_CLASSES.add(String.class);
        SUPPORT_SOURCE_CLASSES.add(Date.class);
        SUPPORT_SOURCE_CLASSES.add(java.sql.Date.class);
        SUPPORT_SOURCE_CLASSES.add(java.sql.Time.class);
        SUPPORT_SOURCE_CLASSES.add(java.sql.Timestamp.class);
        SUPPORT_SOURCE_CLASSES.add(LocalDateTime.class);
        SUPPORT_SOURCE_CLASSES.add(LocalDate.class);
    }

    @Override
    public Long to(Object source, Class<Long> targetType) {
        return DateUtils.milliseconds(source);
    }

    @Override
    public boolean support(Object source, Class<?> targetType) {
        if ( source != null && targetType == Long.class )
            return source instanceof Number || SUPPORT_SOURCE_CLASSES.contains(targetType);
        return false;
    }

}
